package com.wo.cloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/3/29 22:29
 * Description: 自定义配置过滤器
 */

@Component
public class RequestPathGatewayFilterFactory extends AbstractGatewayFilterFactory<RequestPathGatewayFilterFactory.Config> {

    public RequestPathGatewayFilterFactory(){
        super(Config.class);
    }

    // 简化配置方案: RequestPath=name,value
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name","value");
    }


    @Override
    public GatewayFilter apply(Config config) {

        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // 前置处理， 获取请求路径
                String requestPath = exchange.getRequest().getPath().toString();
                System.out.println("请求路径: " + requestPath);


                Mono<Void> filter = chain.filter(exchange);

                // 后置处理
                System.out.println("后置处理");

                return filter;
            }
        };
    }

    public static class Config {

        private String name;
        private String value;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}
